<template>
  <div class="friend-list">
    <div class="search-form">
      <a-form :model="searchForm" layout="inline">
        <a-row :gutter="10">
          <a-col :span="20" style="text-align: right">
            <a-row :gutter="16">
              <a-col :span="8"
                ><a-form-item field="nick" label="昵称">
                  <a-input
                    v-model="searchForm.nick"
                    placeholder="请输入昵称"
                    allow-clear
                    @change="handleSearch"
                  /> </a-form-item
              ></a-col>
              <a-col :span="8"
                ><a-form-item field="remark" label="备注">
                  <a-input
                    v-model="searchForm.remark"
                    placeholder="请输入备注"
                    allow-clear
                    @change="handleSearch"
                  /> </a-form-item
              ></a-col>
              <a-col :span="8"
                ><a-form-item field="phone" label="手机号">
                  <a-input
                    v-model="searchForm.phone"
                    placeholder="请输入手机号"
                    allow-clear
                    @change="handleSearch"
                  /> </a-form-item
              ></a-col>
              <a-col :span="8"
                ><a-form-item field="tags" label="标签">
                  <a-input
                    v-model="searchForm.tags"
                    placeholder="请输入标签"
                    allow-clear
                    @change="handleSearch"
                  /> </a-form-item
              ></a-col>
              <a-col :span="8"
                ><a-form-item field="isfriend" label="好友状态">
                  <a-select
                    v-model="searchForm.isfriend"
                    placeholder="请选择"
                    allow-clear
                    @change="handleSearch"
                  >
                    <a-option :value="1">是好友</a-option>
                    <a-option :value="0">不是对方好友</a-option>
                  </a-select>
                </a-form-item></a-col
              >
              <a-col :span="8"
                ><a-form-item field="isreceive" label="接收群发">
                  <a-select
                    v-model="searchForm.isreceive"
                    placeholder="请选择"
                    allow-clear
                    @change="handleSearch"
                  >
                    <a-option :value="1">接收</a-option>
                    <a-option :value="0">不接收</a-option>
                  </a-select>
                </a-form-item></a-col
              >
            </a-row>
          </a-col>
          <a-divider style="height: 80px" direction="vertical" />
          <a-col flex="88px" style="text-align: right">
            <a-form-item>
              <a-space direction="vertical" fill>
                <a-button type="primary" @click="handleSearch">搜索</a-button>
                <a-button style="margin-left: 8px" @click="handleReset"
                  >重置</a-button
                >
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div style="padding-bottom: 10px">
      <a-space>
        <a-button
          type="primary"
          status="danger"
          :disabled="selectedKeys.length === 0"
          @click="handleBatchDelete"
        >
          批量删除好友
        </a-button>
        <a-button
          type="primary"
          :disabled="selectedKeys.length === 0"
          @click="handlebatchEditFriend"
        >
          批量自动收款
        </a-button>
        <a-button
          type="primary"
          :disabled="selectedKeys.length === 0"
          @click="handleBatchAutoAIReply"
        >
          批量AI回复
        </a-button>
      </a-space>
    </div>
    <a-table
      row-key="wxid"
      :data="friendList"
      :columns="columns"
      :loading="loading"
      :pagination="{
        total: count,
        current: current,
        pageSize: pageSize,
        showTotal: true,
        showPageSize: true,
      }"
      :row-selection="{
        type: 'checkbox',
        showCheckedAll: true,
        onlyCurrent: false,
      }"
      v-model:selectedKeys="selectedKeys"
      @page-change="handlePageChange"
      @page-size-change="handlePageSizeChange"
    >
      <template #wxinfo="{ record }">
        <a-row>
          <a-col :span="6" style="text-align: center"
            ><a-avatar
              :trigger-icon-style="{ color: '#3491FA' }"
              @click="handleGetInfo(record)"
            >
              <img alt="avatar" :src="record.avatarMinUrl" />
              <template #trigger-icon>
                <div v-if="record.sex"><icon-woman /></div
                ><div v-else><icon-man /></div>
              </template>
            </a-avatar>
          </a-col>
          <a-col :span="18">
            <div>昵称：{{ record.nick }} </div>
            <div>微信号：{{ record.wxNum }}</div>
            <div>手机号：{{ record.phome }}</div>
          </a-col>
        </a-row>
      </template>
      <template #remark="{ record }">
        <a-typography-paragraph
          editable
          v-model:editText="record.remark"
          @edit-end="handleEditRemark(record)"
        >
          {{ record.remark }}
        </a-typography-paragraph>
      </template>
      <template #isfriend="{ record }">
        <div v-if="!record.isfriend">不在对方好友中</div>
        <div v-else>是</div>
      </template>
      <template #isconfirmpay="{ record }">
        <a-switch
          :model-value="record.isconfirmpay"
          @change="(value) => handleConfirmpayChange(record, Boolean(value))"
        />
      </template>
      <template #isreceive="{ record }">
        <a-switch
          :model-value="record.isreceive"
          @change="(value) => handleIsreceive(record, Boolean(value))"
        />
      </template>
      <template #isopenai="{ record }">
        <a-switch
          :model-value="record.isopenai"
          @change="(value) => handleAutoChange(record, Boolean(value))"
        />
      </template>
      <template #isvip="{ record }">
        <a-switch
          :model-value="record.isvip"
          @change="(value) => handleVipChange(record, Boolean(value))"
        />
      </template>
      <template #tags="{ record }">
        <a-space wrap>
          <a-tag
            v-for="tag in record.tags"
            :key="tag"
            closable
            @close="handleRemoveTag(record, tag)"
          >
            {{ tag }}
          </a-tag>
          <a-input
            v-if="showInput && editingWxid === record.wxid"
            ref="inputRef"
            v-model="inputVal"
            :style="{ width: '90px' }"
            size="mini"
            @keyup.enter="handleAddTag(record)"
            @blur="handleAddTag(record)"
          />
          <a-tag
            v-else
            :style="{
              backgroundColor: 'var(--color-fill-2)',
              border: '1px dashed var(--color-fill-3)',
              cursor: 'pointer',
            }"
            @click="handleEditTag(record)"
          >
            <template #icon>
              <icon-plus />
            </template>
          </a-tag>
        </a-space>
      </template>
    </a-table>
  </div>
</template>

<script lang="ts" setup>
  import { ref, watch, nextTick } from 'vue';
  import { IconPlus } from '@arco-design/web-vue/es/icon';
  import { Message, Modal,TableColumnData } from '@arco-design/web-vue';
  import {
    getFriendList,
    editFriend,
    editFriendRemark,
    getFriendInfo,
    BatchDelete,
    batchEditFriend,
  } from '@/api/weixin';

  const props = defineProps<{
    wxid: string;
  }>();

  const current = ref(1);
  const pageSize = ref(10);
  const count = ref(0);
  const loading = ref(false);
  const friendList = ref([]);
  const selectedKeys = ref<string[]>([]);

  // 搜索表单数据
  const searchForm = ref({
    nick: '',
    remark: '',
    phone: '',
    tags: '',
    isfriend: undefined as undefined | number,
    isreceive: undefined as undefined | number,
  });

  const columns: TableColumnData[] = [
    {
      title: '基本信息',
      slotName: 'wxinfo',
      width: 250,
    },
    {
      title: '备注',
      slotName: 'remark',
      width: 120,
    },
    {
      title: '微信号',
      dataIndex: 'wxid',
      width: 150,
    },
    {
      title: '标签',
      slotName: 'tags',
      width: 200,
    },
    {
      title: 'vip',
      slotName: 'isvip',
      width: 100,
      align: 'center',
    },
    {
      title: '好友状态',
      slotName: 'isfriend',
      width: 100,
      align: 'center',
    },
    {
      title: '自动收款',
      slotName: 'isconfirmpay',
      width: 100,
      align: 'center',
    },
    {
      title: '群发开关',
      slotName: 'isreceive',
      width: 100,
      align: 'center',
    },
    {
      title: 'AI回复',
      slotName: 'isopenai',
      width: 100,
      align: 'center',
    },
  ];

  // 获取好友列表数据
  const fetchFriendList = async (wxid: string) => {
    loading.value = true;
    try {
      const res: any = await getFriendList(wxid, {
        field: {
          nick: searchForm.value.nick,
          remark: searchForm.value.remark,
          phone: searchForm.value.phone,
          tags: searchForm.value.tags,
          isfriend: searchForm.value.isfriend,
          isreceive: searchForm.value.isreceive,
        },
        page: current.value,
        pageSize: pageSize.value,
      });
      if (res.code === 20000) {
        count.value = res.data.count;
        friendList.value = res.data.list;
      } else {
        Message.error(res.msg || '获取好友列表失败');
      }
    } catch (error) {
      console.error('获取好友列表失败:', error);
    } finally {
      loading.value = false;
    }
  };

  // 处理页码变化
  const handlePageChange = async (page: number) => {
    current.value = page;
    await fetchFriendList(props.wxid);
  };
  // 处理每页条数变化
  const handlePageSizeChange = async (size: number) => {
    pageSize.value = size;
    current.value = 1; // 切换页面大小时重置为第一页
    await fetchFriendList(props.wxid);
  };
  // 搜索处理
  const handleSearch = () => {
    current.value = 1; // 重置页码
    fetchFriendList(props.wxid);
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.value = {
      nick: '',
      remark: '',
      phone: '',
      tags: '',
      isfriend: undefined,
      isreceive: undefined,
    };
    current.value = 1;
    fetchFriendList(props.wxid);
  };

  // 标签编辑相关变量
  const inputRef = ref<HTMLTextAreaElement | null>(null);
  const showInput = ref(false);
  const inputVal = ref('');
  const editingWxid = ref('');

  // 开始编辑标签
  const handleEditTag = (record: any) => {
    editingWxid.value = record.wxid;
    showInput.value = true;

    nextTick(() => {
      if (inputRef.value) {
        inputRef.value.focus();
      }
    });
  };
  // 添加标签
  const handleAddTag = async (record: any) => {
    if (inputVal.value) {
      try {
        // 获取当前标签数组
        const currentTags = [...(record.tags || [])];
        // 添加新标签
        if (!currentTags.includes(inputVal.value)) {
          currentTags.push(inputVal.value);

          const res: any = await editFriend({
            mywxid: props.wxid,
            wxid: record.wxid,
            field: {
              tags: currentTags,
            },
          });

          if (res.code === 20000) {
            Message.success('添加标签成功');
            await fetchFriendList(props.wxid);
          } else {
            Message.error(res.msg || '添加标签失败');
          }
        }
      } catch (error) {
        Message.error('添加标签失败');
      }
    }
    inputVal.value = '';
    showInput.value = false;
    editingWxid.value = '';
  };

  const handleEditRemark = async (record: any) => {
    try {
      const res: any = await editFriendRemark({
        mywxid: props.wxid,
        wxid: record.wxid,
        field: {
          remark: record.remark,
        },
      });

      if (res.code === 20000) {
        Message.success('修改成功');
        await fetchFriendList(props.wxid);
      } else {
        Message.error(res.msg || '修改失败');
      }
    } catch (error) {
      Message.error('修改失败');
    }
  };
  // 移除标签
  const handleRemoveTag = async (record: any, tag: string) => {
    try {
      const currentTags = record.tags.filter((t: string) => t !== tag);

      const res: any = await editFriend({
        mywxid: props.wxid,
        wxid: record.wxid,
        field: {
          tags: currentTags,
        },
      });

      if (res.code === 20000) {
        Message.success('删除标签成功');
        await fetchFriendList(props.wxid);
      } else {
        Message.error(res.msg || '删除标签失败');
      }
    } catch (error) {
      Message.error('删除标签失败');
    }
  };

  const handleGetInfo = async (record: any) => {
    try {
      const res: any = await getFriendInfo({
        mywxid: props.wxid,
        wxid: record.wxid,
      });
      if (res.code === 20000) {
        // friendInfo.value = JSON.stringify(res.data.result, null, 2);
        await fetchFriendList(props.wxid);
      } else {
        Message.error(res.msg || '获取微信信息失败');
      }
    } catch (error) {
      Message.error('获取微信信息失败');
    }
  };

  const handleBatchDelete = async () => {
    if (selectedKeys.value.length === 0) {
      Message.warning('请选择要删除的好友');
      return;
    }

    const handleConfirm = async () => {
      try {
        const res: any = await BatchDelete({
          mywxid: props.wxid,
          wxids: selectedKeys.value,
        });

        if (res.code === 20000) {
          Message.success('批量删除成功');
          selectedKeys.value = []; // 清空选中项
          await fetchFriendList(props.wxid);
        } else {
          Message.error(res.msg || '批量删除失败');
        }
      } catch (error) {
        Message.error('批量删除失败');
      }
    };

    Modal.warning({
      title: '删除确认',
      content: `确定要删除选中的 ${selectedKeys.value.length} 个好友吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: handleConfirm,
    });
  };

  const handlebatchEditFriend = async () => {
    if (selectedKeys.value.length === 0) {
      Message.warning('请选择要设置自动收款的好友');
      return;
    }

    const handleConfirm = async () => {
      try {
        const res: any = await batchEditFriend({
          mywxid: props.wxid,
          wxids: selectedKeys.value, // 注意：接口参数可能需要调整
          field: {
            isconfirmpay: true, // 设置为开启自动收款
          },
        });

        if (res.code === 20000) {
          Message.success('批量设置自动收款成功');
          selectedKeys.value = []; // 清空选中项
          await fetchFriendList(props.wxid); // 刷新列表
        } else {
          Message.error(res.msg || '批量设置失败');
        }
      } catch (error) {
        Message.error('批量设置失败');
      }
    };

    Modal.warning({
      title: '设置确认',
      content: `确定要为选中的 ${selectedKeys.value.length} 个好友开启自动收款吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: handleConfirm,
    });
  };
  // 批量设置AI回复
  const handleBatchAutoAIReply = async () => {
    if (selectedKeys.value.length === 0) {
      Message.warning('请选择要设置AI回复的好友');
      return;
    }

    const handleConfirm = async () => {
      try {
        const res: any = await batchEditFriend({
          mywxid: props.wxid,
          wxids: selectedKeys.value,
          field: {
            isopenai: true, // 设置为开启AI回复
          },
        });

        if (res.code === 20000) {
          Message.success('批量设置AI回复成功');
          selectedKeys.value = []; // 清空选中项
          await fetchFriendList(props.wxid); // 刷新列表
        } else {
          Message.error(res.msg || '批量设置失败');
        }
      } catch (error) {
        Message.error('批量设置失败');
      }
    };

    Modal.warning({
      title: '设置确认',
      content: `确定要为选中的 ${selectedKeys.value.length} 个好友开启AI回复吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: handleConfirm,
    });
  };

  const handleConfirmpayChange = async (record: any, value: boolean) => {
    try {
      const res: any = await editFriend({
        mywxid: props.wxid,
        wxid: record.wxid,
        field: {
          isconfirmpay: value,
        },
      });

      if (res.code === 20000) {
        Message.success('设置成功');
        // 刷新列表数据
        await fetchFriendList(props.wxid);
      } else {
        Message.error(res.msg || '设置失败');
      }
    } catch (error) {
      Message.error('设置失败');
      // 如果失败，恢复开关状态
      record.isconfirmpay = !value;
    }
  };

  const handleIsreceive = async (record: any, value: boolean) => { 
    try {
      const res: any = await editFriend({
        mywxid: props.wxid,
        wxid: record.wxid,
        field: {
          isreceive: value,
        },
      });

      if (res.code === 20000) {
        Message.success('设置成功');
        // 刷新列表数据
        await fetchFriendList(props.wxid);
      } else {
        Message.error(res.msg || '设置失败');
      }
    } catch (error) {
      Message.error('设置失败');
      // 如果失败，恢复开关状态
      record.isconfirmpay = !value;
    }
  };
  const handleAutoChange = async (record: any, value: boolean) => {
    try {
      const res: any = await editFriend({
        mywxid: props.wxid,
        wxid: record.wxid,
        field: {
          isopenai: value,
        },
      });

      if (res.code === 20000) {
        Message.success('设置成功');
        // 刷新列表数据
        await fetchFriendList(props.wxid);
      } else {
        Message.error(res.msg || '设置失败');
      }
    } catch (error) {
      Message.error('设置失败');
      // 如果失败，恢复开关状态
      record.isconfirmpay = !value;
    }
  };

  const handleVipChange = async (record: any, value: boolean) => {
    try {
      const res: any = await editFriend({
        mywxid: props.wxid,
        wxid: record.wxid,
        field: {
          isvip: value,
        },
      });

      if (res.code === 20000) {
        Message.success('设置成功');
        // 刷新列表数据
        await fetchFriendList(props.wxid);
      } else {
        Message.error(res.msg || '设置失败');
      }
    } catch (error) {
      Message.error('设置失败');
      // 如果失败，恢复开关状态
      record.isconfirmpay = !value;
    }
  };
  // 监听wxid变化获取好友列表
  watch(
    () => props.wxid,
    async (newVal) => {
      if (newVal) {
        await fetchFriendList(newVal);
      }
    },
    { immediate: true }
  );
</script>

<style scoped>
  .friend-list {
    width: 100%;
  }

  .search-form {
    padding: 16px;
    background-color: var(--color-bg-2);
    border-radius: 4px;
  }

  :deep(.arco-form-item-layout-inline) {
    margin-right: 16px;
    margin-bottom: 16px;
  }
</style>
